/******************************************************************************

    Simple Authentication and Authorisation System (SAAS)

    pkt.c

    Copyright (C) 2011  Josh Goes


    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    If you require a mailing address for this software, please send your
    mail to the following address:
        SAAS
        GPO Box 2973
        BRISBANE QLD 4001
        AUSTRALIA

******************************************************************************/



#include "saas-build.h"

#include <string.h>


void pkt_req( saas_t *inst , uint32_t *trans_id , uint8_t *pkt , uint16_t *pkt_len , uint32_t reqresp , uint16_t type , uint8_t *payload , uint16_t payload_len )
{
	*trans_id = gen_trans_id( );

	pkt_hdr_t *pkt_hdr   = (pkt_hdr_t *) pkt;
	pkt_hdr->magic_id    = u32tonet( reqresp );
	pkt_hdr->trans_id    = u32tonet( *trans_id );
	pkt_hdr->type        = u16tonet( type );
	pkt_hdr->_reserved0  = 0;
	pkt_hdr->_reserved1  = 0;
	pkt_hdr->payload_len = u16tonet( payload_len );
	memcpy( pkt + sizeof( pkt_hdr_t ) , payload , payload_len );

	// set the used packet length.
	*pkt_len = sizeof( pkt_hdr_t ) + payload_len;

	sha256( pkt , pkt + 32 , *pkt_len - 32 );
}



uint16_t pkt_resp( saas_t *inst , uint32_t trans_id , uint8_t *pkt , uint16_t pkt_len )
{
	pkt_hdr_t *hdr = (pkt_hdr_t *) pkt;

	if ( hdr->magic_id != SAAS_MAGIC_RESP )
		return SAAS_OP_DECRYPT_ERROR;

	hdr->type        = u16fromnet( hdr->type );
	hdr->trans_id    = u32fromnet( hdr->trans_id );
	hdr->payload_len = u16fromnet( hdr->payload_len );

	if ( hdr->payload_len == 0 )
		return SAAS_OP_DECRYPT_ERROR;

	if ( hdr->trans_id != trans_id )
		return SAAS_OP_DECRYPT_ERROR;

	return SAAS_OP_SUCCESS;
}


